package com.zhouyou.http.demo.view;


import com.zhouyou.http.ohos.MainThreadDisposable;
import com.zhouyou.http.ohos.Notification;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.Observer;
import ohos.agp.components.Component;
import ohos.eventhandler.EventRunner;

public class ViewClickObservable extends Observable<Object> {
    private final Component view;

    public ViewClickObservable(Component view) {
        this.view = view;
    }

    @Override
    protected void subscribeActual(@NonNull Observer<? super Object> observer) {
        if (!checkMainThread(observer)) {
            return;
        }
        Listener listener = new Listener(view, observer);
        observer.onSubscribe(listener);
        view.setClickedListener(listener);
    }


    public static boolean checkMainThread(Observer<?> observer) {
        if (EventRunner.current() != EventRunner.getMainEventRunner()) {
            observer.onError(new IllegalStateException(
                    "Expected to be called on the main thread but was " + Thread.currentThread().getName()));
            return false;
        }
        return true;
    }

    static final class Listener extends MainThreadDisposable implements Component.ClickedListener {
        private final Component view;
        private final Observer<? super Object> observer;

        Listener(Component view, Observer<? super Object> observer) {
            this.view = view;
            this.observer = observer;
        }

        @Override
        public void onClick(Component v) {
            if (!isDisposed()) {
                observer.onNext(Notification.INSTANCE);
            }
        }

        @Override
        protected void onDispose() {
            view.setClickedListener(null);
        }


    }
}
